<template>
  <div id="video">
    <header>
      <div class="top">
        <div class="left">
          <van-icon name="arrow-left" @click="handleBack" />
          <div class="author">
            <div class="author-avatar"><img :src="videoInfo.author.icon" alt=""></div>
            <div class="author-name">{{ videoInfo.author.name }}</div>
          </div>
        </div>
        <div class="right">
          <van-icon v-if="!isFollowed" name="plus" @click="handleFollow" />
        </div>
      </div>

      <video ref="videoRef" :src="videoInfo.playUrl" controls autoplay muted playsinline
        @timeupdate="handleTimeUpdate"></video>

      <nav>
        <div :class="{ active: currentSection === 'introduction' }" @click="switchSection('introduction')">简介</div>
        <div :class="{ active: currentSection === 'comment' }" @click="switchSection('comment')">评论</div>
      </nav>

    </header>

    <main>
      <div class="sections-container">
        <div class="introduction-section"
          :class="{ 'active': currentSection === 'introduction', 'inactive': currentSection === 'comment' }">
          <div class="video-info">
            <div class="video-title">{{ videoInfo.title }}</div>
            <div class="video-tag"><span v-for="item in videoInfo.tags">#{{ item.name }}</span></div>
            <div class="video-desc-wrapper">
              <div ref="descElement" class="video-desc" :class="{ 'expanded': isDescExpanded }">
                {{ videoInfo.description }}
              </div>

              <div v-if="showExpandButton" class="expand-btn" @click="toggleDescExpand">
                <van-icon name="arrow-down" :class="{ 'rotated': isDescExpanded }" />
              </div>
            </div>

            <div class="video-data-icon">
              <div class="item" @click="handleLike" :class="{ 'liked': isLiked }">
                <van-icon :name="isLiked ? 'good-job' : 'good-job-o'" />
                <span>{{ formatCount(displayCollectionCount) }}</span>
              </div>
              <div class="item" @click="handleFavorite" :class="{ 'favorited': isFavorited }">
                <van-icon :name="isFavorited ? 'star' : 'star-o'" />
                <span>{{ displayFavoriteCount }}</span>
              </div>
              <div class="item" @click="switchSection('comment')">
                <van-icon name="chat-o" />
                <span>{{ videoInfo.consumption.replyCount }}</span>
              </div>
              <div class="item" @click="handleDownload" :class="{ 'downloading': isDownloading }">
                <van-icon name="back-top" style="transform: rotate(180deg);" />
                <span>{{ isDownloading ? `${downloadProgress}%` : '下载' }}</span>
              </div>
              <div class="item">
                <van-icon name="share-o" />
                <span>{{ formatCount(videoInfo.consumption.shareCount) }}</span>
              </div>
            </div>

            <div class="related-videos-section" v-if="relatedVideosList.length > 0">
              <RelatedList :items="relatedVideosList.slice(0, 10)" @item-click="handleRelatedVideoClick" />
            </div>

            <div v-if="relatedVideosList.length === 0"
              style="padding: 20px; color: #888; font-size: 12px; text-align: center;">
              暂无相关推荐
            </div>
          </div>
        </div>
      </div>

      <div class="comment-section"
        :class="{ 'active': currentSection === 'comment', 'inactive': currentSection === 'introduction' }">
        <CommentList :items="commentList" title="评论" :has-more="!!nextPageUrl" :loading="loadingComments" theme="dark"
          @load-more="loadMoreComments" />
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { defineOptions } from 'vue'

defineOptions({
  name: 'Video'
})

import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useVideoStore } from '@/stores/counter'
import { useWatchHistoryStore } from '@/stores/watchHistory'
import { useFavoritesStore } from '@/stores/favorites'
import { useFollowsStore } from '@/stores/follows'
import { getVideoDetail, getVideoReplies, getByFullUrl, getRelatedVideos } from '@/api/api'
import CommentList from '@/components/CommentList.vue'
import RelatedList from '@/components/RelatedList.vue'
import { showToast } from 'vant'

const route = useRoute()
const router = useRouter()
const videoStore = useVideoStore()
const watchHistoryStore = useWatchHistoryStore()
const favoritesStore = useFavoritesStore()
const followsStore = useFollowsStore()

// 响应式数据
const loading = ref(false)
const loadingComments = ref(false)
const isDescExpanded = ref(false)
const descElement = ref<HTMLElement | null>(null)
const showExpandButton = ref(false)
const currentSection = ref<'introduction' | 'comment'>('introduction')
const videoRef = ref<HTMLVideoElement | null>(null)
const isDownloading = ref(false)
const downloadProgress = ref(0)

// 计算属性
const videoInfo = computed(() => {
  return videoStore.videoDetail || videoStore.currentVideo
})

// 点赞状态
const isLiked = ref(false)
const likeCountIncrement = ref(0)

// 收藏数字增量
const favoriteCountIncrement = ref(0)

// 检查是否已收藏
const isFavorited = computed(() => {
  if (!videoInfo.value?.id) return false
  return favoritesStore.isFavorited(videoInfo.value.id)
})

// 检查是否已关注
const isFollowed = computed(() => {
  if (!videoInfo.value?.author?.id) return false
  return followsStore.isFollowed(videoInfo.value.author.id)
})

// 显示的点赞数（原始值 + 增量）
const displayCollectionCount = computed(() => {
  const baseCount = videoInfo.value?.consumption?.collectionCount || 0
  return baseCount + likeCountIncrement.value
})

// 显示的收藏数（原始值 + 增量）
const displayFavoriteCount = computed(() => {
  const baseCount = videoInfo.value?.consumption?.realCollectionCount || 0
  return baseCount + favoriteCountIncrement.value
})

const commentList = computed(() => {
  const list = videoStore.commentList
  return list
})
const nextPageUrl = computed(() => videoStore.nextPageUrl)

// 相关推荐列表
const relatedVideosList = computed(() => {
  return videoStore.relatedList
})


// 获取视频ID
const getVideoId = (): string | number | null => {
  if (route.params.id) {
    return route.params.id as string | number
  }
  const video = videoStore.currentVideo || videoStore.videoDetail
  if (video?.id) {
    return video.id
  }
  return null
}

// 加载视频详情
const loadVideoDetail = async () => {
  const videoId = getVideoId()
  if (!videoId) {
    console.error('视频ID不存在')
    return
  }

  // 检查当前视频ID是否与store中的视频ID匹配，如果不匹配则清空旧数据
  const currentVideoId = videoStore.videoDetail?.id || videoStore.currentVideo?.id
  if (currentVideoId && String(currentVideoId) !== String(videoId)) {
    videoStore.clearVideoDetail()
    videoStore.setCurrentVideo(null)
  }

  // 在加载新视频时，先清空评论列表和相关推荐
  videoStore.setCommentList([])
  videoStore.setNextPageUrl(null)
  videoStore.setRelatedList([])

  loading.value = true

  try {
    // 并行请求视频详情、评论、相关推荐
    const [detailRes, repliesRes, relatedRes] = await Promise.all([
      getVideoDetail(videoId),
      getVideoReplies(videoId),
      getRelatedVideos(videoId)
    ])

    // 处理视频详情数据
    let processedVideoDetail = null
    if (detailRes) {
      processedVideoDetail = detailRes
      videoStore.setVideoDetail(detailRes)
      if ((detailRes as any).playUrl) {
        videoStore.setCurrentVideo({
          ...(detailRes as any),
          playUrl: (detailRes as any).playUrl
        })
      }
    }

    // 处理评论数据
    let processedCommentList: any[] = []
    let processedNextPageUrl: string | null = null
    const repliesData = repliesRes as any

    if (repliesData?.itemList && Array.isArray(repliesData.itemList)) {
      processedCommentList = repliesData.itemList
      processedNextPageUrl = repliesData.nextPageUrl || null
      videoStore.setCommentList(repliesData.itemList)
      videoStore.setNextPageUrl(processedNextPageUrl)
    } else {
      // 如果没有评论数据，确保清空列表
      videoStore.setCommentList([])
      videoStore.setNextPageUrl(null)
    }

    // 处理相关推荐数据
    const relatedData = relatedRes as any
    let validItems: any[] = []

    if (relatedData?.itemList && Array.isArray(relatedData.itemList)) {
      // 过滤出有效的视频项
      validItems = relatedData.itemList.filter((item: any) => {
        const videoData = item.data || item
        return videoData && (videoData.id || videoData.videoId) && videoData.cover
      })
      videoStore.setRelatedList(validItems)
    } else if (Array.isArray(relatedData)) {
      // 如果直接返回数组
      validItems = relatedData.filter((item: any) => {
        const videoData = item.data || item
        return videoData && (videoData.id || videoData.videoId) && videoData.cover
      })
      videoStore.setRelatedList(validItems)
    } else {
      videoStore.setRelatedList([])
    }

    // 数据加载完成后检查文本是否超出
    await checkIfTextOverflow()

  } catch (error) {
    console.error('加载视频详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载更多评论
const loadMoreComments = async () => {
  if (!nextPageUrl.value || loadingComments.value) return

  loadingComments.value = true

  try {
    const res = await getByFullUrl(nextPageUrl.value)
    const resData = res as any

    if (resData?.itemList) {
      const newComments = resData.itemList
      videoStore.appendCommentList(newComments)
      videoStore.setNextPageUrl(resData.nextPageUrl || null)
    }
  } catch (error) {
    console.error('加载更多评论失败:', error)
  } finally {
    loadingComments.value = false
  }
}

// 检查文本是否超出3行
const checkIfTextOverflow = async () => {
  await nextTick()
  if (descElement.value && videoInfo.value?.description) {
    // 保存当前展开状态
    const originalExpanded = isDescExpanded.value

    // 临时设置为折叠状态来检查
    isDescExpanded.value = false
    await nextTick()

    // 获取折叠状态下的实际内容高度和显示区域高度
    const scrollHeight = descElement.value.scrollHeight
    const clientHeight = descElement.value.clientHeight

    // 计算3行高度
    const lineHeight = parseFloat(getComputedStyle(descElement.value).lineHeight) || (parseFloat(getComputedStyle(descElement.value).fontSize) * 1.5)
    const maxHeight = lineHeight * 3

    // 判断是否超出3行
    showExpandButton.value = scrollHeight > maxHeight

    // 恢复原展开状态
    isDescExpanded.value = originalExpanded
    await nextTick()
  } else {
    showExpandButton.value = false
  }
}

// 切换section
const switchSection = (section: 'introduction' | 'comment') => {
  if (currentSection.value === section) return

  currentSection.value = section
}

// 格式化数字显示（大于10000转换为W格式）
const formatCount = (count: number | undefined | null): string => {
  if (!count || count === 0) return '0'
  if (count >= 10000) {
    const w = count / 10000
    // 保留一位小数，如果小数部分为0则不显示小数
    const decimal = w % 1
    if (decimal === 0) {
      return `${Math.floor(w)}W`
    }
    // 保留一位小数
    return `${w.toFixed(1)}W`
  }
  return count.toString()
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 处理相关视频点击
const handleRelatedVideoClick = async (item: any) => {
  const videoData = item.data || item
  const videoId = videoData?.id || videoData?.videoId
  if (!videoId) {
    console.error('相关视频数据无效:', item)
    return
  }

  // 重置状态
  isLiked.value = false
  likeCountIncrement.value = 0
  favoriteCountIncrement.value = 0
  isDescExpanded.value = false
  currentSection.value = 'introduction'

  // 更新路由参数，触发重新加载
  await router.push({
    name: 'video',
    params: { id: String(videoId) }
  })

  // 滚动到顶部
  await nextTick()
  const mainElement = document.querySelector('main')
  if (mainElement) {
    mainElement.scrollTop = 0
  }
}

// 处理点赞
const handleLike = () => {
  if (!videoInfo.value) return

  if (!isLiked.value) {
    // 点赞：数字加一
    isLiked.value = true
    likeCountIncrement.value = 1
  } else {
    // 取消点赞：数字减一
    isLiked.value = false
    likeCountIncrement.value = 0
  }
}

// 处理收藏/取消收藏
const handleFavorite = () => {
  const video = videoInfo.value
  if (!video) return

  // 检查登录状态
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  if (!isLoggedIn) {
    showToast('请先登录')
    return
  }

  const wasFavorited = isFavorited.value
  const success = favoritesStore.toggleFavorite(video)
  if (success) {
    if (!wasFavorited) {
      // 刚收藏，数字加一
      favoriteCountIncrement.value += 1
      showToast('已收藏')
    } else {
      // 取消收藏，数字减一
      favoriteCountIncrement.value = Math.max(0, favoriteCountIncrement.value - 1)
      showToast('已取消收藏')
    }
  }
}

// 处理关注
const handleFollow = () => {
  const video = videoInfo.value
  if (!video || !video.author) return

  // 检查登录状态
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  if (!isLoggedIn) {
    showToast('请先登录')
    return
  }

  const author = {
    id: video.author.id || video.author.userId || '',
    name: video.author.name || '未知',
    icon: video.author.icon || '',
    description: video.author.description || ''
  }

  if (!author.id) {
    showToast('作者信息不完整')
    return
  }

  const wasFollowed = isFollowed.value
  const success = followsStore.toggleFollow(author)

  if (success) {
    if (!wasFollowed) {
      showToast('关注成功')
    } else {
      showToast('已取消关注')
    }
  }
}

const handleDownload = async () => {
  const videoId = getVideoId()
  if (!videoId) {
    showToast('视频ID不存在')
    return
  }

  const video = videoInfo.value
  if (!video || !video.playUrl) {
    showToast('视频信息不存在')
    return
  }

  // 如果正在下载，则取消
  if (isDownloading.value) {
    showToast('下载中，请稍候...')
    return
  }

  try {
    isDownloading.value = true
    downloadProgress.value = 0

    // 检查是否支持下载API
    if (!('showSaveFilePicker' in window)) {
      // 使用传统下载方式
      await downloadVideoWithProgress(video.playUrl, video.title || `video_${videoId}`)
    } else {
      // 使用现代 File System Access API
      await downloadVideoWithFileSystemAPI(video.playUrl, video.title || `video_${videoId}`)
    }

    showToast('下载完成')
  } catch (error: any) {
    console.error('下载失败:', error)
    if (error.name !== 'AbortError') {
      showToast(error.message || '下载失败')
    }
  } finally {
    isDownloading.value = false
    downloadProgress.value = 0
  }
}

// 使用传统方式下载视频
const downloadVideoWithProgress = async (url: string, filename: string) => {
  try {
    const response = await fetch(url)

    if (!response.ok) {
      throw new Error('下载失败：网络错误')
    }

    const contentLength = response.headers.get('content-length')
    const total = contentLength ? parseInt(contentLength, 10) : 0

    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('下载失败：无法读取视频流')
    }

    const chunks: Uint8Array[] = []
    let received = 0

    while (true) {
      const { done, value } = await reader.read()

      if (done) break

      if (value) {
        chunks.push(value)
        received += value.length

        if (total > 0) {
          downloadProgress.value = Math.round((received / total) * 100)
        }
      }
    }

    // 合并所有chunks
    const blob = new Blob(chunks as BlobPart[], { type: 'video/mp4' })

    // 创建下载链接
    const downloadUrl = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = `${filename}.mp4`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    // 清理URL对象
    setTimeout(() => {
      URL.revokeObjectURL(downloadUrl)
    }, 100)
  } catch (error: any) {
    throw new Error(error.message || '下载失败')
  }
}

// 使用现代 File System Access API 下载
const downloadVideoWithFileSystemAPI = async (url: string, filename: string) => {
  try {
    // @ts-ignore
    const fileHandle = await window.showSaveFilePicker({
      suggestedName: `${filename}.mp4`,
      types: [{
        description: 'MP4视频文件',
        accept: { 'video/mp4': ['.mp4'] }
      }]
    })

    const response = await fetch(url)
    if (!response.ok) {
      throw new Error('下载失败：网络错误')
    }

    const contentLength = response.headers.get('content-length')
    const total = contentLength ? parseInt(contentLength, 10) : 0

    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('下载失败：无法读取视频流')
    }

    const writable = await fileHandle.createWritable()
    let received = 0

    while (true) {
      const { done, value } = await reader.read()

      if (done) break

      if (value) {
        await writable.write(value)
        received += value.length

        if (total > 0) {
          downloadProgress.value = Math.round((received / total) * 100)
        }
      }
    }

    await writable.close()
  } catch (error: any) {
    // 如果用户取消选择文件，不显示错误
    if (error.name === 'AbortError') {
      throw error
    }
    // 如果不支持File System Access API，回退到传统方式
    if (error.name === 'TypeError' || error.name === 'NotAllowedError') {
      await downloadVideoWithProgress(url, filename)
    } else {
      throw new Error(error.message || '下载失败')
    }
  }
}

// 切换展开/收起
const toggleDescExpand = async () => {
  if (!descElement.value) return

  if (!isDescExpanded.value) {
    // 展开动画
    // 先设置展开状态以获取完整内容
    isDescExpanded.value = true
    await nextTick()

    if (descElement.value) {
      // 获取实际内容高度
      const actualHeight = descElement.value.scrollHeight
      // 先设置为当前高度（3行高度）
      const lineHeight = parseFloat(getComputedStyle(descElement.value).lineHeight) || (parseFloat(getComputedStyle(descElement.value).fontSize) * 1.5)
      const currentHeight = lineHeight * 3
      descElement.value.style.maxHeight = `${currentHeight}px`

      // 强制重排，然后设置为目标高度，触发动画
      await nextTick()
      requestAnimationFrame(() => {
        if (descElement.value) {
          descElement.value.style.maxHeight = `${actualHeight}px`
        }
      })
    }
  } else {
    // 收起动画
    if (descElement.value) {
      // 获取当前实际高度
      const currentHeight = descElement.value.scrollHeight
      descElement.value.style.maxHeight = `${currentHeight}px`

      await nextTick()

      // 计算3行高度
      const lineHeight = parseFloat(getComputedStyle(descElement.value).lineHeight) || (parseFloat(getComputedStyle(descElement.value).fontSize) * 1.5)
      const targetHeight = lineHeight * 3

      // 设置目标高度，触发收起动画
      requestAnimationFrame(() => {
        if (descElement.value) {
          descElement.value.style.maxHeight = `${targetHeight}px`

          // 动画结束后，切换状态并清除内联样式
          setTimeout(() => {
            isDescExpanded.value = false
            nextTick(() => {
              if (descElement.value) {
                descElement.value.style.maxHeight = ''
              }
            })
          }, 400) // 等待动画完成
        }
      })
    }
  }
}

// 监听路由变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    loadVideoDetail()
  }
}, { immediate: true })

// 监听视频信息变化，检查文本是否超出
watch(() => videoInfo.value?.description, () => {
  if (videoInfo.value?.description) {
    checkIfTextOverflow()
  }
}, { immediate: true })

// 自动播放视频
const autoPlayVideo = async () => {
  await nextTick()
  if (videoRef.value && videoInfo.value?.playUrl) {
    videoRef.value.muted = true
    try {
      await videoRef.value.play()
      // 视频开始播放时，添加观看记录
      if (videoInfo.value) {
        watchHistoryStore.addHistory(videoInfo.value)
      }
    } catch (error) {
      console.error('自动播放失败:', error)
    }
  }
}

// 监听视频播放进度，更新观看记录
const handleTimeUpdate = () => {
  if (videoRef.value && videoInfo.value?.id) {
    const currentTime = Math.floor(videoRef.value.currentTime)
    watchHistoryStore.updateWatchProgress(videoInfo.value.id, currentTime)
  }
}

// 监听视频信息变化，自动播放
watch(() => videoInfo.value?.playUrl, (newUrl) => {
  if (newUrl) {
    autoPlayVideo()
  }
}, { immediate: true })

// 加载相关推荐数据（独立函数，用于在已有视频详情时单独加载）
const loadRelatedVideos = async (videoId: string | number) => {
  try {
    const relatedRes = await getRelatedVideos(videoId)
    const relatedData = relatedRes as any
    let validItems: any[] = []

    if (relatedData?.itemList && Array.isArray(relatedData.itemList)) {
      validItems = relatedData.itemList.filter((item: any) => {
        const videoData = item.data || item
        return videoData && (videoData.id || videoData.videoId) && videoData.cover
      })
      videoStore.setRelatedList(validItems)
    } else if (Array.isArray(relatedData)) {
      validItems = relatedData.filter((item: any) => {
        const videoData = item.data || item
        return videoData && (videoData.id || videoData.videoId) && videoData.cover
      })
      videoStore.setRelatedList(validItems)
    } else {
      videoStore.setRelatedList([])
    }


  } catch (error) {
    console.error('加载相关推荐失败:', error)
    videoStore.setRelatedList([])
  }
}

// 生命周期
onMounted(async () => {
  const videoId = getVideoId()
  if (!videoId) {
    console.warn('onMounted: 视频ID不存在')
    return
  }

  // 检查当前视频ID是否与store中的视频ID匹配
  const currentVideoId = videoStore.videoDetail?.id || videoStore.currentVideo?.id
  if (!currentVideoId || String(currentVideoId) !== String(videoId)) {
    // ID不匹配，加载完整详情（包括相关推荐）
    await loadVideoDetail()
  } else {
    // ID匹配，但需要检查是否需要加载相关推荐
    if (!videoStore.relatedList || videoStore.relatedList.length === 0) {
      // 如果没有相关推荐数据，单独加载
      await loadRelatedVideos(videoId)
    } else {
      // 如果已有相关推荐数据，直接输出验证
      console.log('视频ID:', videoId)
      console.log('相关推荐数据:', videoStore.relatedList)
    }

    if (!videoStore.commentList || videoStore.commentList.length === 0) {
      // 如果评论列表为空，重新加载评论
      const currentVideoId = getVideoId()
      if (currentVideoId) {
        try {
          loadingComments.value = true
          const repliesRes = await getVideoReplies(currentVideoId)
          const repliesData = repliesRes as any
          if (repliesData?.itemList && Array.isArray(repliesData.itemList)) {
            videoStore.setCommentList(repliesData.itemList)
            videoStore.setNextPageUrl(repliesData.nextPageUrl || null)
          } else {
            console.warn('onMounted: 评论数据格式不正确:', repliesData)
            videoStore.setCommentList([])
            videoStore.setNextPageUrl(null)
          }
        } catch (error) {
          console.error('onMounted: 重新加载评论失败:', error)
          videoStore.setCommentList([])
          videoStore.setNextPageUrl(null)
        } finally {
          loadingComments.value = false
        }
      }
    }
    // 检查文本溢出
    await checkIfTextOverflow()
  }
  // 尝试自动播放
  await autoPlayVideo()
})

// console.log(videoInfo.value);

</script>

<style scoped lang="less">
#video {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #000;
  color: #fff;
  overflow: hidden;
}

video {
  width: 100%;
}

header {
  width: 100%;
  flex-shrink: 0;

  .top {
    height: 5vh;
    padding: 0 3vw;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
      height: 100%;
      display: flex;
      align-items: center;
      gap: 3vw;

      i {
        font-size: 18px;
        cursor: pointer;
        transition: opacity 0.2s;

        &:hover {
          opacity: 0.7;
        }

        &:active {
          opacity: 0.5;
        }
      }

      .author {
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 10px;
        gap: 2vw;

        .author-avatar {
          height: 70%;
          aspect-ratio: 1/1;
          border-radius: 50%;
          position: relative;

          img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
          }

          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            right: 0;
            height: 30%;
            aspect-ratio: 1/1;
            background-color: #09b3e7;
            border-radius: 50%;
          }
        }
      }
    }

    .right {
      border: 1px solid #fff;
      border-radius: 4px;
      padding: 0.5vw;
      font-size: 12px;
    }
  }

  nav {
    height: 4vh;
    display: flex;
    align-items: center;
    gap: 6vw;
    font-size: 12px;
    font-weight: 350;
    padding: 0 3vw;
    border-bottom: 1px solid #ffffff1a;

    div {
      padding-bottom: 2px;

      &.active {
        border-bottom: 1px solid #fff;
      }
    }
  }
}

main {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
  padding-top: 2vh;

  .sections-container {
    position: relative;
    width: 100%;
  }

  .introduction-section {
    width: 100%;
    transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    transform: translateX(0);

    &.inactive {
      transform: translateX(-100%);
    }

    .video-info {
      padding: 0 3vw;
      box-sizing: border-box;

      .video-title {
        font-size: 14px;
      }

      .video-tag {
        font-size: 10px;
        padding: 2vh 0;
        color: #ffffff56;

        span {
          margin-right: 1vw;
        }
      }

      .video-desc-wrapper {
        position: relative;
        padding-bottom: 6vh;

        .video-desc {
          font-size: 11px;
          line-height: 1.5;
          overflow: hidden;
          max-height: calc(1.5em * 3);
          transition: max-height 0.4s cubic-bezier(0.4, 0, 0.2, 1);
          position: relative;

          display: -webkit-box;
          -webkit-line-clamp: 3;
          line-clamp: 3;
          -webkit-box-orient: vertical;
          text-overflow: ellipsis;

          &.expanded {
            display: block;
            -webkit-line-clamp: unset;
            line-clamp: unset;
            text-overflow: clip;
          }
        }

        .expand-btn {
          position: absolute;
          right: 0;
          bottom: 0;
          background: linear-gradient(to right, transparent, #000 30%);
          padding: 5px 0 5px 15px;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: flex-end;

          i {
            font-size: 12px;
            transition: transform 0.3s ease;
            background-color: #2c2c2c;
            border-radius: 50%;
            padding: 2px;

            &.rotated {
              transform: rotate(180deg);
            }
          }
        }
      }

      .video-data-icon {
        width: 100%;
        padding: 2vh 6vw;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 18px;

        .item {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 2px;
          cursor: pointer;
          transition: opacity 0.2s;

          &:hover {
            opacity: 0.7;
          }

          &.favorited {
            color: #ffd700;
          }

          &.liked {
            color: #ff6b6b;
          }

          &:active {
            opacity: 0.5;
          }

          &.downloading {
            color: #09b3e7;
            animation: pulse 1.5s ease-in-out infinite;
          }

          span {
            font-size: 10px;
          }
        }

        @keyframes pulse {

          0%,
          100% {
            opacity: 1;
          }

          50% {
            opacity: 0.6;
          }
        }
      }

      .related-videos-section {
        margin-top: 2vh;
        padding-top: 2vh;
        border-top: 1px solid rgba(255, 255, 255, 0.1);
      }
    }
  }

  .comment-section {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    transform: translateX(100%);

    &.active {
      transform: translateX(0);
    }
  }
}
</style>
